﻿#region
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using EndlessDownloader.Engine;
using EndlessDownloader.Properties;

#endregion

namespace EndlessDownloader
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (DesignMode)
                return;
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (DesignMode)
                return;

            Text = string.Format("{0} ({1})", Text, WinformUtility.GetPublishVersionText());

//#if DEBUG
//#else            
            using (var form = new AboutForm())
            {
                if (form.ShowDialog() != DialogResult.OK)
                    return;
            }

            using (StartForm form = new StartForm())
            {
                if (form.ShowDialog() != DialogResult.OK)
                    return;
            }
//#endif

            bgwWorker.RunWorkerAsync();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Settings.Default.Save();

            base.OnClosing(e);
        }

        private readonly WebClient _webClient = new WebClient();

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStop.Enabled = false;
            bgwWorker.CancelAsync();                                                                 
        }

        private void bgwWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int page = Settings.Default.StartPage;
            int downloadIndex = 0;

            while (true)
            {
                bgwWorker.ReportProgress((int) Progress.Start, page);


                string url = "http://kv86.tumblr.com/page/" + page;

                string html = _webClient.DownloadString(url);
                var imageUrls = ImageSourceParser.Instance.ExtractImageUrl(html, Settings.Default.NoPorn);

                List<Picture> pictures = new List<Picture>(imageUrls.Count);
                foreach (var imageUrl in imageUrls)
                {
                    downloadIndex++;

                    Picture picture = new Picture();
                    picture.DownloadIndex = downloadIndex;
                    picture.Url = imageUrl;
                    picture.FileName = downloadIndex.ToString("D" + Settings.Default.FileNameDigit) + Path.GetExtension(imageUrl);
                    picture.SavePath = Path.Combine(Settings.Default.SaveFolder, picture.FileName);

                    pictures.Add(picture);
                }

                bgwWorker.ReportProgress((int) Progress.Page, pictures);


                foreach (var picture in pictures)
                {
                    _webClient.DownloadFile(picture.Url, picture.SavePath);

                    bgwWorker.ReportProgress((int) Progress.File, picture);

                    if (Settings.Default.DownloadInterval > 0)
                        Thread.Sleep(Settings.Default.DownloadInterval * 1000);

                    if (bgwWorker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                }

                if (bgwWorker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                
                page++;
            }
        }

        private void bgwWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (((Progress) e.ProgressPercentage) == Progress.Start)
            {
                int page = (int) e.UserState;
                lblPage.Text = string.Format("페이지 {0:N0}", page);
                uscPageViewer.ShowLoadingLabel();
            }
            else if (((Progress) e.ProgressPercentage) == Progress.Page)
            {
                List<Picture> pictures = (List<Picture>) e.UserState;
                uscPageViewer.Initialize(pictures);
            }
            else if (((Progress) e.ProgressPercentage) == Progress.File)
            {
                Picture picture = (Picture) e.UserState;
                uscPageViewer.SetAsCompleted(picture.DownloadIndex);
                uscImageNavigator.AddToMaximum(picture.DownloadIndex, picture.SavePath);
            }
        }

        private void bgwWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        private enum Progress
        {
            Start,
            Page,
            File
        }

        private void mnuHelp_Click(object sender, EventArgs e)
        {
            Process.Start(Settings.Default.HelpUrl);
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}